package com.yoomiito.app.ui.order.sureorder.singleGoods;

import static androidx.core.view.ViewKt.postDelayed;

import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.yoomiito.app.Constant;
import com.yoomiito.app.R;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.AppConfig;
import com.yoomiito.app.base.WebViewActivity;
import com.yoomiito.app.model.bean.AddressInfo;
import com.yoomiito.app.model.bean.AppInterfaceInfo;
import com.yoomiito.app.model.my.MyRemainMoneyInfo;
import com.yoomiito.app.model.order.CreateOrderInfo;
import com.yoomiito.app.model.order.PayResultInfo;
import com.yoomiito.app.net.YmApi;
import com.yoomiito.app.base.BaseActPresenter;
import com.yoomiito.app.pay.PayTypeUtils;
import com.yoomiito.app.ui.goods.GoodsInfoActivity;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.NetworkUtils;
import com.yoomiito.app.utils.ResUtil;
import com.yoomiito.app.utils.RouterUtils;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.widget.dialog.AccountCancelDialog;
import com.yoomiito.app.widget.dialog.AlipayH5Dialog;

import org.json.JSONException;
import org.reactivestreams.Publisher;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.log.XLog;
import cn.droidlover.xdroidmvp.net.ApiException;
import cn.droidlover.xdroidmvp.net.ApiSubscriber;
import cn.droidlover.xdroidmvp.net.BaseModel;
import cn.droidlover.xdroidmvp.net.XApi;
import io.reactivex.functions.Function;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

@Deprecated
public class BuyGoodsPresenter extends BaseActPresenter<BuyGoodsActivity> {

    public BuyGoodsPresenter(AppConfig appConfig) {
        super(appConfig);
    }



    public void createOrder(String productId, String consignee, String provinceId,
                            String cityId, String countryId, String areaName, String tel, String address,
                            String note, int num,int addressType,int type,int payType,String good) {
        if (NetworkUtils.checkNetPermission(getV())) {
            return;
        }
        LinkedHashMap<String, Object> params = new LinkedHashMap<>();
        params.put("consignee", consignee);
        params.put("goodsList", good);
        params.put("payType", payType);
        params.put("type", type);
        params.put("addressType", addressType);
        if(addressType == 1){
            params.put("city", cityId);
            params.put("province", provinceId);
            params.put("county", countryId);
            params.put("area_name", areaName);
            params.put("address", address);
        }
        params.put("mobile", tel);
        if(!TextUtils.isEmpty(note)){
            params.put("note", note);
        }
        params.put("exchangeNum",0);
        params.put("systemType",1);
        L.i("参数:" + params.toString());
        RequestBody body = RequestBody.create(YmApi.JSON, JSONObject.toJSONString(params));
        YmApi.getYmService()
                .order(body)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getScheduler())
                .compose(XApi.getApiTransformerData())
                .subscribe(new ApiSubscriber<PayResultInfo>() {
                    @Override
                    public void onSuccess(PayResultInfo payResultInfo) {

                    }

                    @Override
                    public void onFail(ApiException error) {
                        if (!TextUtils.isEmpty(error.getMsg())) {
                            YMToast.showText(error.getMsg());
                        }
                        if (getV() == null) return;
                        getV().dismissLoading();
                        if (error.getCode() == ApiException.PAY_PSW_ERROR) {
                            getV().error(true, ResUtil.getString(R.string.psw_error));
                        } else if (error.getCode() == ApiException.BALANCE_INSUFFICIENT) {
                            getV().error(ResUtil.getString(R.string.balance_poor));
                        } else if (error.getCode() == ApiException.YOUMI_INSUFFICIENT) {//优米数量不足
                            getV().error(error.getMsg());
                            getV().showLoading();
                            getRemain();
                        } else {
                            getV().error(false, "");
                            EventMessage eventMessage = new EventMessage();
                            eventMessage.setCode(AllCode.Fail);
                            getV().payResult(eventMessage);
                        }
                    }
                });

    }


    public void getInterface(String url,String consignee, String provinceId,
                             String cityId, String countryId, String areaName, String tel, String address,
                             String note, int num,int addressType,int type,int payType,String good) {

        LinkedHashMap<String, Object> params = new LinkedHashMap<>();
        params.put("consignee", consignee);
        params.put("goodsList", good);
        params.put("payType", payType);
        params.put("type", type);
        params.put("addressType", addressType);
        if(addressType == 1){
            params.put("city", cityId);
            params.put("province", provinceId);
            params.put("county", countryId);
            params.put("area_name", areaName);
            params.put("address", address);
        }
        params.put("mobile", tel);
        if(!TextUtils.isEmpty(note)){
            params.put("note", note);
        }
        params.put("exchangeNum",0);
        params.put("systemType",1);
        L.e("参数:" + params.toString());
        RequestBody body = RequestBody.create(YmApi.JSON, JSONObject.toJSONString(params));
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(YmApi.BaseUrl + url)
                .addHeader("Authorization", SharedPref.getInstance(App.getInstance()).getString(Constant.TOKEN, ""))
                .header("Site", "app_mugwort_android") //
                .header("Platform", "")
                .post(body)
                .build();
        Call call = client.newCall(request);
        XLog.e(YmApi.BaseUrl + url + "===");
        call.enqueue(new Callback() {
            // 2
            @Override
            public void onFailure(Call call, IOException e) {
                //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                getV().dismissLoading();
                getV().error(false, "");
                EventMessage eventMessage = new EventMessage();
                eventMessage.setCode(AllCode.Fail);
                getV().payResult(eventMessage);
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (getV() == null) return;
                getV().dismissLoading();
                // 3
                try {
                    org.json.JSONObject obj = new org.json.JSONObject(response.body().string());
                    String data = obj.getString("data");
                    if (obj.getInt("code") == 200) {
                        PayResultInfo payResultInfo = new Gson().fromJson(data, PayResultInfo.class);
                        if ("accountpay".equals(payResultInfo.getPay_type()) || "offlinepay".equals(payResultInfo.getPay_type())) {
                            EventMessage eventMessage = new EventMessage();
                            eventMessage.setCode(AllCode.Success);
                            getV().payResult(eventMessage);
                        }  else if("fast_pay".equals(payResultInfo.getPay_type())){
                            Intent intent = new Intent(getV(), WebViewActivity.class);
                            intent.putExtra(Constant.DATA, payResultInfo.getData().getFastPay_order());
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            getV().startActivity(intent);
                        } else {
                            getV().dismissLoading();
                            getV().mQueryOrderID = payResultInfo.getOut_trade_no();
                            getV().pay_type = payResultInfo.getPay_type();
                            if ("wxpay".equals(payResultInfo.getPay_type())) {
                                PayTypeUtils.wxPay(payResultInfo.getData());
                            } else {
                                if("alipay_h5".equals(payResultInfo.getPay_type())){

                                    getV().setShow();
                                    Intent intent = new Intent(getV(), WebViewActivity.class);
                                    intent.putExtra(Constant.DATA, payResultInfo.getData().getAlipay_order());
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    getV().startActivity(intent);

                                }else{
                                    PayTypeUtils.aliPay(getV(), payResultInfo.getData().getAlipay_order());
                                }
                            }
                        }
                    }else{
//                        getV().error(true, obj.getString("msg") );
                        EventMessage eventMessage = new EventMessage();
                        eventMessage.setCode(AllCode.Fail);
                        getV().payResult(eventMessage);
                        getV().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    YMToast.showText(obj.getString("msg") );
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        });
                    }
                    XLog.e("======="+response.body().string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


    }







//    public void createOrder1(String productId, String consignee, String provinceId,
//                            String cityId, String countryId, String areaName, String tel, String address,
//                            String note, int num,int addressType,int type,int payType,String good) {
//        if (NetworkUtils.checkNetPermission(getV())) {
//            return;
//        }
//        LinkedHashMap<String, Object> params = new LinkedHashMap<>();
//        params.put("consignee", consignee);
//        params.put("goodsList", good);
//        params.put("payType", payType);
//        params.put("type", type);
//        params.put("addressType", addressType);
//        params.put("city", cityId);
//        params.put("province", provinceId);
//        params.put("county", countryId);
//        params.put("area_name", areaName);
//        params.put("mobile", tel);
//        params.put("address", address);
//        if(!TextUtils.isEmpty(note)){
//            params.put("note", note);
//        }
//        params.put("exchangeNum",0);
//        params.put("systemType",1);
//        L.i("参数:" + params.toString());
//        RequestBody body = RequestBody.create(YmApi.JSON, JSONObject.toJSONString(params));
//        YmApi.getYmService()
//                .createOrder(body)
//                .compose(getV().bindToLifecycle())
//                .compose(XApi.getApiTransformerData())
//                .flatMap((Function<CreateOrderInfo, Publisher<BaseModel<MyRemainMoneyInfo>>>) str -> {
//                    if (hasV()) {
//                        getV().mPayOrderId = str.getId();
//                        getV().mPayMoney = str.getAmount_paid();
//                    }
//                    return YmApi.getYmService().getMoneyAgent();
//                })
//
////                .subscribe(new ApiSubscriber<CreateOrderInfo>() {
////                    @Override
////                    public void onSuccess(CreateOrderInfo createOrderInfo) {
////                        getV().mPayOrderId = createOrderInfo.getId();
////                        getV().mPayMoney = createOrderInfo.getAmount_paid();
////                        getV().showPayDialog();
////                    }
////
////                    @Override
////                    public void onFail(ApiException error) {
////
////                    }
////                });
//                .compose(XApi.getApiTransformerData())
//                .compose(XApi.getScheduler())
//                .subscribe(new ApiSubscriber<MyRemainMoneyInfo>(handleException()) {
//                    @Override
//                    public void onSuccess(MyRemainMoneyInfo data) {
//                        if (hasV()) {
//                            getV().dismissLoading();
//                            data.setShowYoumi(false);
//                            getV().setYouMi(data);
//                            getV().showPayDialog();
////                        getV().orderId = orderResult.getOut_trade_no();
////                        PayTypeUtils.wxPay(orderResult);
//                        }
//                    }
//
//                    @Override
//                    public void onFail(ApiException error) {
//                        if (hasV()) {
//                            getV().dismissLoading();
//                        }
//                    }
//                });
//    }

    public void getRemain() {
        YmApi.getYmService()
                .getMoneyAgent()
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<MyRemainMoneyInfo>(handleException()) {
                    @Override
                    public void onSuccess(MyRemainMoneyInfo data) {
                        if (hasV()) {
                            getV().dismissLoading();
                            data.setShowYoumi(true);
                            getV().setYouMi(data);
//                        getV().orderId = orderResult.getOut_trade_no();
//                        PayTypeUtils.wxPay(orderResult);
                        }
                    }

                    @Override
                    public void onFail(ApiException error) {
                        if (hasV()) {
                            getV().dismissLoading();
                            YMToast.showText("优米数量获取失败 请稍后再试");
                            getV().finish();
                        }
                    }
                });
    }

    public void pay(String id, int wx, int ali, String account, int orderType, String psw, int deduction_account) {
        L.i("支付金额: " +
                "\nid:" + id +
                " \nwx:" + wx +
                " \nali:" + ali +
                " \naccount:" + account +
                " \norderType:" + orderType +
                " \npsw:" + psw +
                " \ndeduction_account:" + deduction_account);
        YmApi.getYmService()
                .multipPay(id, wx, ali, account, orderType, psw, String.valueOf(deduction_account))
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<PayResultInfo>() {
                    @Override
                    public void onSuccess(PayResultInfo payResultInfo) {
                        if (getV() == null) return;
                        if ("accountpay".equals(payResultInfo.getPay_type())) {
                            EventMessage eventMessage = new EventMessage();
                            eventMessage.setCode(AllCode.Success);
                            getV().payResult(eventMessage);
                        } else {
                            getV().dismissLoading();
                            getV().mQueryOrderID = payResultInfo.getOut_trade_no();
                            getV().pay_type = payResultInfo.getPay_type();
                            if ("wxpay".equals(payResultInfo.getPay_type())) {
                                PayTypeUtils.wxPay(payResultInfo.getData());
                            } else {
                                if("alipay_h5".equals(payResultInfo.getPay_type())){

                                    getV().setShow();
                                    Intent intent = new Intent(getV(), WebViewActivity.class);
                                    intent.putExtra(Constant.DATA, payResultInfo.getData().getAlipay_order());
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    getV().startActivity(intent);

                                }else{
                                    PayTypeUtils.aliPay(getV(), payResultInfo.getData().getAlipay_order());
                                }
                            }

                        }
                    }

                    @Override
                    public void onFail(ApiException error) {
                        if (!TextUtils.isEmpty(error.getMsg())) {
                            YMToast.showText(error.getMsg());
                        }
                        if (getV() == null) return;
                        getV().dismissLoading();
                        if (error.getCode() == ApiException.PAY_PSW_ERROR) {
                            getV().error(true, ResUtil.getString(R.string.psw_error));
                        } else if (error.getCode() == ApiException.BALANCE_INSUFFICIENT) {
                            getV().error(ResUtil.getString(R.string.balance_poor));
                        } else if (error.getCode() == ApiException.YOUMI_INSUFFICIENT) {//优米数量不足
                            getV().error(error.getMsg());
                            getV().showLoading();
                            getRemain();
                        } else {
                            getV().error(false, "");
                            EventMessage eventMessage = new EventMessage();
                            eventMessage.setCode(AllCode.Fail);
                            getV().payResult(eventMessage);
                        }
                    }
                });
    }

    //获取当前余额
    public void getIsAgent() {
        YmApi.getYmService()
                .getMoneyAgent()
                .compose(getV().bindToLifecycle())
                .compose(XApi.<MyRemainMoneyInfo>getApiTransformerData())
                .compose(XApi.<MyRemainMoneyInfo>getScheduler())
                .subscribe(new ApiSubscriber<MyRemainMoneyInfo>() {
                    @Override
                    public void onSuccess(MyRemainMoneyInfo data) {

                    }

                    @Override
                    public void onFail(ApiException error) {
                        YMToast.showText(error.getMsg());
                    }
                });
    }

    public void queryOrder(String orderId, String pay_type) {
        if (NetworkUtils.checkNetPermission(getV())) {
            return;
        }
        EventMessage eventMessage = new EventMessage();
        YmApi.getYmService()
                .quseryOrderStatus(orderId, pay_type)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerNoData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<BaseModel>(handleException()) {
                    @Override
                    public void onSuccess(BaseModel baseModel) {
                        if (getV() == null) return;
                        eventMessage.setCode(AllCode.Success);
                        getV().payResult(eventMessage);
                    }

                    @Override
                    public void onFail(ApiException error) {
                        if (getV() == null) return;
                        eventMessage.setCode(AllCode.Fail);
                        getV().payResult(eventMessage);
                    }
                });
    }


    public void getAddress() {
        YmApi.getYmService()
                .getAddressList(1)
                .compose(getV().bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(new ApiSubscriber<List<AddressInfo>>() {
                    @Override
                    public void onSuccess(List<AddressInfo> addressInfo) {
//                        if (addressInfos.size()==0){

                        if (addressInfo.size() == 0) {
                            getV().showAddressView(new AddressInfo());
                        } else {
                            int j = 0;
                            for (int i = 0; i < addressInfo.size(); i++) {
                                if (TextUtils.equals(addressInfo.get(i).getIsDefault(), "1")) {
                                    j = i;
                                }
                            }
                            getV().showAddressView(addressInfo.get(j));
                        }


//                        }else {
//                            for (AddressInfo addressInfo:addressInfos) {
//                                if ("1".equals(addressInfo.getIsDefault())){
//                                    getV().showAddressView(addressInfo);
//                                }
//                            }
//                        }
                    }

                    @Override
                    public void onFail(ApiException error) {
                        getV().dismissLoading();
                        if (!TextUtils.isEmpty(error.getMsg())) {
                            YMToast.showText(error.getMsg());
                        }
                    }
                });
    }

}
